﻿using System;
using System.Configuration;
using log4net;

namespace Sireass.Dal
{
	/// <summary>
	/// Esta clase se encarga de crear el manejador de la capa de acceso a datos configurado en la aplicación.
	/// </summary>
    public static class DalFactory
    {
		// Create a logger for use in this class
		private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static Type _dalType;

		/// <summary>
		/// Permite obtener el manejador de la capa de acceso a datos configurado en la aplicación.
		/// </summary>
		/// <returns>IDalManager, el manejador de la capa de acceso a datos</returns>
        public static IDalManager GetManager()
        {
            if (_dalType == null)
            {
                var dalTypeName = ConfigurationManager.AppSettings["DalManagerType"];
				if (log.IsDebugEnabled)
				{
					log.Debug("dalTypeName: " + dalTypeName);
				}
				if (!string.IsNullOrEmpty(dalTypeName))
				{
					_dalType = Type.GetType(dalTypeName);
					if (log.IsDebugEnabled)
					{
						log.Debug("_dalType: " + _dalType);
					}
				}
				else
					throw new NullReferenceException("DalManagerType");
                if (_dalType == null)
                    throw new ArgumentException(string.Format("Type {0} could not be found", dalTypeName));
            }
            return (IDalManager)Activator.CreateInstance(_dalType);
        }
    }
}
